import Vue from 'vue';
import iView from 'iview';
import Util from '@/libs/util';
import VueRouter from 'vue-router';
import Cookies from 'js-cookie';
import http from '@/libs/httpUtils';
import {isURL} from '@/libs/validate';

Vue.use(VueRouter);

// 全局路由
const globalRouters = [
  {path: '/404', name: '404', meta: {title: '404-页面不存在'}, component: () => import('@/views/error-page/404.vue')},
  {
    path: '/500',
    name: '500',
    meta: {title: '500-服务端错误'},
    component: () => import('@/views/error-page/500.vue'),
    props: true
  },
  {path: '/403', name: '403', meta: {title: '403-权限不足'}, component: () => import('@/views/error-page/403.vue')},
  {path: '/401', name: '401', meta: {title: '401-token过期'}, component: () => import('@/views/error-page/401.vue')},
  {path: '/login', name: 'login', meta: {title: '登录'}, component: () => import('@/views/login.vue')}
];

// 主路由（需要嵌套上左右整体布局）
const mainRouters = {
  path: '/',
  name: 'main',
  meta: {title: '主入口整体布局'},
  component: () => import('@/views/main.vue'),
  redirect: {name: 'home'},
  children: [
    {path: '/home', name: 'home', meta: {title: '首页'}, component: () => import('@/views/home/home.vue')},
    {
      path: '/ownspace',
      name: 'ownspace',
      meta: {title: '个人中心', menuId: -99},
      component: () => import('@/views/own-space/own-space.vue')
    },
    {
      path: '/error-page',
      name: 'errorPage',
      meta: {title: '错误页面预览', menuId: -98},
      component: () => import('@/views/modules/error-page.vue')
    }
  ],
  beforeEnter (to, from, next) { // 进入路由前需要获取token，token放入cookies可以验证有效期
    let token = Cookies.get('token');
    if (!token || !/\S/.test(token)) { // \S匹配非空白字符 ， \s匹配空白字符
      next({name: 'login'});
    }
    next();
  }
};

// 路由配置
const RouterConfig = {
  mode: 'hash',
  scrollBehavior: () => ({y: 0}),
  isAddDynamicMenuRoutes: false, // 是否已经添加动态(菜单)路由
  routes: globalRouters.concat(mainRouters)
};

const router = new VueRouter(RouterConfig);

// 进入路由前
router.beforeEach((to, from, next) => {
  iView.LoadingBar.start();
  // debugger
  Util.title(to.meta.title);
  // debugger
  // 添加动态路由：1、已经添加或全局路由，直接访问 2、获取菜单列表，添加并保存本地存储
  if (router.options.isAddDynamicMenuRoutes || routerUtil.getCurrentRouterType(to) === 'global') {
    // bug todo：当组件未创建或未导入时，路由无法import，此时需要跳转到404，下边的代码通过import判断组件是否存在，暂不清楚系统开销
    /* if (routerUtil.getCurrentRouterType(to) === 'global') {
        next();
    } else {
        if (to.name !== 'home') {
            let name = to.name.replace('-', '/');
            import(`@/views/modules/${name}`).then(() => {
                next();
            }).catch(() => {
                next({name: '404'});
            });
        } else {
            next();
        }
    } */
    next();
  } else {
    http({
      url: http.adornUrl('/sys/menu/nav'),
      method: 'get',
      params: http.adornParams()
    }).then(({data}) => {
      if (data && data.code === 0) { // 接口调用成功
        routerUtil.addDynamicMenuRouters(data.menuList); // 添加动态路由
        router.options.isAddDynamicMenuRoutes = true;
        sessionStorage.setItem('menuList', JSON.stringify(data.menuList || '[]'));
        sessionStorage.setItem('permissions', JSON.stringify(data.permissions || '[]'));
        next({...to, replace: true}); // 页面跳转
      } else {
        sessionStorage.setItem('menuList', '[]');
        sessionStorage.setItem('permissions', '[]');
        // next({ name: '500', params: { errorMsg: data.code } });// 服务端错误
        next();
      }
    });
  }
});

// 路由完成后
router.afterEach((to) => {
  // Util.openNewPage(router.app, to.name, to.params, to.query);
  iView.LoadingBar.finish();
  window.scrollTo(0, 0);
});

let routerUtil = {
  /* 路由处理工具 */
};
// 判断当前路由类型: global: 全局路由， main: 主入口路由
routerUtil.getCurrentRouterType = function (route) {
  let temp = [];
  /* globalRouters.forEach((item) => { // forEach循环无法中断，除非通过抛异常的方式，或是使用Array.some或 Array.every
      if (route.path === item.path) {
          return 'global';
      } else if (item.children && item.children.length >= 1) {
          temp = temp.concat(item.children);
      }
  }); */
  for (let i = 0; i < globalRouters.length; i++) {
    if (route.path === globalRouters[i].path) {
      return 'global'
    } else if (globalRouters[i].children && globalRouters[i].children.length >= 1) {
      temp = temp.concat(globalRouters[i].children)
    }
  }
  return temp.length >= 1 ? this.getCurrentRouterType(route, temp) : 'main';
};

/**
 * 添加动态路由
 * @param menuList 菜单列表
 * @param routers 递归创建的动态路由
 */
routerUtil.addDynamicMenuRouters = function (menuList = [], routers = []) {
  let temp = [];
  menuList.forEach((item, index) => {
    if (item.list && item.list.length >= 1) {
      temp = temp.concat(item.list);
    }
    if (item.url && /\S/.test(item.url)) { // \S匹配非空白字符
      item.url = item.url.replace(/^\//, ''); // ^\/表示以'/'开头的url
      let route = {
        path: item.url.replace('/', '-'), // /sys/user -> sys-user
        component: null,
        name: item.url.replace('/', '-'),
        meta: {
          menuId: item.menuId,
          title: item.name,
          isDynamic: true,
          isTab: true,
          iframeUrl: ''
        }
      };
      // url以http[s]://开头，通过iframe展示
      if (isURL(item.url)) {
        route.path = `i-${item.menuId}`; // `是延展操作符,字符串拼接 ES2015
        route.name = `i-${item.menuId}`;
        route.meta.iframeUrl = item.url;
      } else {
        route.component = () => import(`@/views/modules/${item.url}`) || null; // 设置跳转组件页面
      }
      routers.push(route);
    }
  });
  if (temp.length >= 1) {
    this.addDynamicMenuRouters(temp, routers);
  } else {
    mainRouters.name = 'main-dynamic';
    mainRouters.children = routers;
    // mainRouters.children = mainRouters.children.concat(routers);
    router.addRoutes([
      mainRouters,
      {path: '*', redirect: {name: '404'}}
    ]);
    sessionStorage.setItem('dynamicMenuRoutes', JSON.stringify(mainRouters.children || '[]'));
    // console.log('\n%c!<-------------------- 动态(菜单)路由 s -------------------->', 'color:blue');
    // console.log(mainRouters.children);
    // console.log('%c!<-------------------- 动态(菜单)路由 e -------------------->\n\n', 'color:blue');
  }
};

export default router;
